package com.zhou.cloud.aop.aspect;

import com.zhou.cloud.annotation.RedisLock;
import com.zhou.cloud.annotation.ZookeeperLock;
import com.zhou.cloud.service.IDistributedLockService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @descrition:
 * @author: zhouyongjun
 * @date: 2022/11/2
 **/
@Aspect
@Component
@Slf4j
public class RedisLockAspect {
    @Autowired
    @Qualifier("redisDistributedLockService")
    IDistributedLockService lockService;
    @Pointcut("@annotation(com.zhou.cloud.annotation.RedisLock)")
    public void cutpoint(){}

    @Around("cutpoint()")
    public Object execute(ProceedingJoinPoint pjp) throws Throwable {
        Method method = ((MethodSignature)pjp.getSignature()).getMethod();
        RedisLock annotation = method.getAnnotation(RedisLock.class);
        boolean isLock = false;
        try {
            isLock = lockService.tryLock(annotation.key(),annotation.requestId(),annotation.timeUnit(),annotation.expireTime(),annotation.waitTime());
            if (!isLock) {
                throw new Exception();
            }
            return pjp.proceed();
        } finally {
            if(isLock){
                lockService.releaseLock(annotation.key(),annotation.requestId());
            }
        }
    }
}
